package com.example.chess.game;

import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 房间管理器
 */
@Component
@Data
public class RoomManager {
    // 组织房间
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();

    // 映射玩家和房间号
    private ConcurrentHashMap<Integer, String> userRoom = new ConcurrentHashMap<>();

    // 观战人员和房间号
    private ConcurrentHashMap<Integer, String> watches = new ConcurrentHashMap<>();

    // 添加房间
    public void add(Room room, int userId1, int userId2){
        rooms.put(room.getRoomId(), room);
        userRoom.put(userId1, room.getRoomId());
        userRoom.put(userId2, room.getRoomId());
    }

    // 移除房间
    public void remove(String roomId, int userId1, int userId2){
        rooms.remove(roomId);
        userRoom.remove(userId1);
        userRoom.remove(userId2);
    }

    // 查找房间
    public Room getRoomById(String roomId){
        return rooms.get(roomId);
    }

    // 根据玩家 ID获取房间
    public Room getRoomByUser(int userId){
        String roomId = userRoom.get(userId);
        if (roomId == null){
            return null;// 未找到
        }
        return rooms.get(roomId);
    }

    // 增加观战
    public void enterWatch(Integer userId, String roomId){
        watches.put(userId, roomId);
    }
    // 出队列
    public void outWatch(Integer userId){
        watches.remove(userId);
    }
    // 根据用户查找观战的房间
    public String getRoomToWatch(int userId){
        return watches.get(userId);
    }
}
